package com.cloudeasy.label.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cloudeasy.api.util.EntityUtil;
import com.cloudeasy.api.vo.label.LabelVO;
import com.cloudeasy.api.vo.PageResult;
import com.cloudeasy.label.field.LabelField;
import com.cloudeasy.label.po.Label;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 标签工具类
 */
public class LabelUtil {
    /**
     * 构造查询
     *
     * @param ids      标签Id列表
     * @param names    标签名称列表
     * @param statuses 状态列表
     * @param asc      正序排序字段
     * @param desc     倒序排序字段
     * @return {@link QueryWrapper<Label>}
     */
    public static QueryWrapper<Label> compose(List<String> ids, List<String> names, List<String> statuses, String[] asc, String[] desc) {
        QueryWrapper<Label> queryWrapper = new QueryWrapper<>();
        if (ids != null && ids.size() > 0) {
            queryWrapper.in("id", ids);
        }
        if (names != null && names.size() > 0) {
            queryWrapper.and(labelQueryWrapper -> {
                names.forEach(name -> labelQueryWrapper.or(labelTempQueryWrapper -> labelTempQueryWrapper.like("name", name)));
                return labelQueryWrapper;
            });
        }
        if (statuses != null && statuses.size() > 0) {
            queryWrapper.in("status", statuses);
        }
        if (asc != null && asc.length > 0) {
            EntityUtil.checkParamter(LabelField.getFieldList(), asc);
            queryWrapper.orderByAsc(asc);
        }
        if (desc != null && desc.length > 0) {
            EntityUtil.checkParamter(LabelField.getFieldList(), desc);
            queryWrapper.orderByDesc(desc);
        }
        return queryWrapper;
    }

    /**
     * 转换VO对象
     *
     * @param label {@link Label}
     * @return {@link LabelVO}
     */
    public static LabelVO convert(Label label) {
        LabelVO labelVO = new LabelVO();
        BeanUtils.copyProperties(label, labelVO);
        return labelVO;
    }

    /**
     * 转换VO对象
     *
     * @param labels {@link List<Label>}
     * @return {@link List<LabelVO>}
     */
    public static List<LabelVO> convert(List<Label> labels) {
        return labels.stream().map(LabelUtil::convert).collect(Collectors.toList());
    }

    /**
     * 转换VO对象
     *
     * @param labelIPage {@link IPage<Label>}
     * @return {@link PageResult<LabelVO>}
     */
    public static PageResult<LabelVO> convert(IPage<Label> labelIPage) {
        PageResult<LabelVO> labelVOPageResult = new PageResult<>();
        labelVOPageResult.setTotal(labelIPage.getTotal())
                .setPages(labelIPage.getPages())
                .setRecords(labelIPage.getRecords().stream().map(LabelUtil::convert).collect(Collectors.toList()));
        return labelVOPageResult;
    }
}
